package com.chujian.framework.starter.mybatis;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.chujian.framework.mybatis.plugins.FormatSqlInterceptor;
import com.chujian.framework.mybatis.plugins.QueryDataAuthInterceptor;
import com.chujian.framework.mybatis.tenant.ChujianTenantLineHandler;
import com.chujian.framework.mybatis.tenant.TenantProperties;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * MybatisPlus 配置文件
 */
@Configuration
@MapperScan(value = {"com.chujian.*.mapper", "com.chujian.*.*.mapper"})
@EnableConfigurationProperties(TenantProperties.class)
public class MybatisPlusAutoConfiguration {

    @Autowired
    private TenantProperties tenantProperties;

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();

        PaginationInnerInterceptor paginationInterceptor = new PaginationInnerInterceptor();

        interceptor.addInnerInterceptor(new FormatSqlInterceptor());

        // 查询权限
        interceptor.addInnerInterceptor(new QueryDataAuthInterceptor());

        // 多租户
        if (tenantProperties.getEnable()) {
            interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new ChujianTenantLineHandler(tenantProperties)));
        }

        // 分页插件
        interceptor.addInnerInterceptor(paginationInterceptor);

        return interceptor;
    }

}

